package com.example.demo.service.impl;

import java.text.MessageFormat;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.example.demo.config.PropertiesConfig;
import com.example.demo.entity.AccessToken;
import com.example.demo.repository.AccessTokenRepository;
import com.example.demo.service.AccessTokenService;

@Service
public class AccessTokenServiceImpl extends BaseServiceImpl<AccessToken> implements AccessTokenService{
	
	protected final Logger logger= LoggerFactory.getLogger(getClass());
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private PropertiesConfig propertiesConfig;
	
	@Autowired
	private AccessTokenRepository accessTokenRepository;
	
	@SuppressWarnings("unchecked")
	@Override
	public AccessToken generateAccessToken() throws Exception{
		//获取微信appId、appSecret、urlToken参数
		String urlToken = propertiesConfig.getUrlToken();
		String appId = propertiesConfig.getAppId();
		String appSecret = propertiesConfig.getAppSecret();
		String url = MessageFormat.format(urlToken, appId,appSecret);
		//访问微信accessToken接口
		Map<String,Object> apiResult;
		String accessToken="";
		int expiresIn=0;
		try {
			apiResult = restTemplate.getForObject(url, Map.class);
			logger.info("微信accessToken接口返回值：{}",apiResult);
			
		} catch (Exception e) {
			throw new Exception("调用微信accessToken接口失败，"+e.getMessage());
		}
//		   解析微信接口返回值
//		 1.正常结果
//		 {access_token=34_grgOvQ7Dr6UY4K9DjE1iewFi5YXSuHEm4STHDggv8_VcqfZCwgYXryv17xiuDLOD3W7Y55-LpzwvKCYO3sLvnMehwQwBt2AjcNGbxZVfUa9qenaXCKVPfElZL12AAb1y_hqGl3n1BPwWxB6HRXCcAGAEKP, expires_in=7200}
//		 2.appId不正确
//		 {errcode=40013, errmsg=invalid appid hints: [6EOCFBiCe-ekY_FA!]}
//		 3.appSecret不正确
//		 {errcode=40125, errmsg=invalid appsecret, view more at http://t.cn/RAEkdVq hint: [.fOCG.wgE-u4xDRa]}
//		 4.{errcode=41004, errmsg=appsecret missing hint: [rfOCH8VgE-Go]}
		try {
			if(StringUtils.isEmpty((String)apiResult.get("access_token"))) {
				throw new Exception("微信接口返回错误码信息："+apiResult);
			}
			accessToken = (String)apiResult.get("access_token");
			expiresIn = (int)apiResult.get("expires_in");
		} catch (Exception e) {
			throw new Exception("微信接口返回值未解析到accessToken，原因："+e.getMessage());
		}
		String id = propertiesConfig.getAppId();
		AccessToken entity = new AccessToken();
		entity.setId(id);
		entity.setAccessToken(accessToken);
		entity.setExpiresIn(expiresIn);
		entity.setUpdated(System.currentTimeMillis());
		accessTokenRepository.save(entity);
		return entity;
	}
}
